﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using MiniX.Manage.Data;
using Aliyun.OSS;
using Microsoft.IdentityModel.Tokens;

namespace MiniX.Manage.Controllers
{
    /// <summary>
    /// 版权所有: Copyright © 2023 Cloudin. 保留所有权利。
    /// 内容摘要: 上传处理类
    /// 创建日期：2023年4月9日
    /// 更新日期：2023年4月21日
    /// 版    本：V1.0.86 
    /// 作    者：Cloudin
    /// </summary>
    public class UploadController : BaseController<UploadController>
    {
        public UploadController(MiniXManageContext context) : base(context)
        {

        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UploadImg(string catalogue, bool open_breviary)
        {
            var files = Request.Form.Files;
            var formFile = files[0];
            var file_name = formFile.FileName;
            var temp_path = GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.UploadImgSavePath) + "\\" + DateTime.Now.Year + "\\" + DateTime.Now.ToString("MMdd") + "\\";
            var extension = Path.GetExtension(file_name);
            var file_name_new = DateTime.Now.ToString("yyyyMMddHHmmss") + MiniX.Utility.Helper.CommonHelper.GenerateRandomNum(6);
            var save_path = temp_path + file_name_new + extension;
            var returnPath = "/" + DateTime.Now.Year + "/" + DateTime.Now.ToString("MMdd") + "/" + file_name_new + extension;

            try
            {
                if (!Directory.Exists(temp_path))
                {
                    Directory.CreateDirectory(temp_path);
                }

                if (System.IO.File.Exists(save_path))
                {
                    System.IO.File.Delete(save_path);
                }

                using (FileStream fs = System.IO.File.Create(save_path))
                {
                    await formFile.CopyToAsync(fs);
                    fs.Flush();
                    fs.Close();
                }

                using FileStream fi = new FileStream(save_path, FileMode.Open);

                // 上传至阿里云OSS
                try
                {
                    OssClient client = new OssClient(GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunEndpoint), GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunAccessKeyId), GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunAccessKeySecret));
                    var key = "upload/" + DateTime.Now.Year + "/" + DateTime.Now.ToString("MMdd") + "/";
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        client.PutObject(GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunBucketName), key, memStream);
                    }
                    ObjectMetadata metadata = new ObjectMetadata();
                    metadata.ContentType = Request.Form.Files[0].ContentType;
                    client.PutObject(GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunBucketName), key + file_name_new + extension, fi, metadata);
                }
                catch (Exception ex)
                {
                    return Json(new { code = 0, errcode = 40014, errmsg = ex.Message });
                }

                return Json(new { code = 0, msg = "上传成功", path = "/upload" + returnPath, data = new { src = GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunCallbackServer) + "upload" + returnPath, title = "" } });
            }
            catch (Exception ex)
            {
                return Json(new { code = 0, errcode = 40014, errmsg = ex.Message });
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UploadFile()
        {
            var files = Request.Form.Files;
            var formFile = files[0];
            var file_name = formFile.FileName;
            var temp_path = GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.UploadImgSavePath) + "\\" + DateTime.Now.Year + "\\" + DateTime.Now.ToString("MMdd") + "\\";
            var extension = Path.GetExtension(file_name);
            var file_name_new = DateTime.Now.ToString("yyyyMMddHHmmss") + MiniX.Utility.Helper.CommonHelper.GenerateRandomNum(6);
            var save_path = temp_path + file_name_new + extension;
            var return_path = "/" + DateTime.Now.Year + "/" + DateTime.Now.ToString("MMdd") + "/" + file_name_new + extension;

            try
            {
                if (!Directory.Exists(temp_path))
                {
                    Directory.CreateDirectory(temp_path);
                }

                if (System.IO.File.Exists(save_path))
                {
                    System.IO.File.Delete(save_path);
                }

                using (FileStream fs = System.IO.File.Create(save_path))
                {
                    await formFile.CopyToAsync(fs);
                    fs.Flush();
                    fs.Close();
                }

                using FileStream fi = new FileStream(save_path, FileMode.Open);

                // 上传至阿里云OSS
                try
                {
                    OssClient client = new OssClient(GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunEndpoint), GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunAccessKeyId), GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunAccessKeySecret));
                    var key = "upload/" + DateTime.Now.Year + "/" + DateTime.Now.ToString("MMdd") + "/";
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        client.PutObject(GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunBucketName), key, memStream);
                    }
                    ObjectMetadata metadata = new ObjectMetadata();
                    metadata.ContentType = Request.Form.Files[0].ContentType;
                    client.PutObject(GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunBucketName), key + file_name_new + extension, fi, metadata);
                }
                catch (Exception ex)
                {
                    return Json(new { code = 0, errcode = 40014, errmsg = ex.Message });
                }

                return Json(new { code = 0, msg = "上传成功", path = "/upload" + return_path, return_path, name = file_name_new, old_name = file_name, local_path = save_path, data = new { src = GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunCallbackServer) + "/upload" + return_path, title = "" } });
            }
            catch (Exception ex)
            {
                return Json(new { code = 0, errcode = 40014, errmsg = ex.Message });
            }
        }

        /// <summary>
        /// 后台富文本编辑器上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Editor()
        {
            var files = Request.Form.Files;
            var formFile = files[0];
            var file_name = formFile.FileName;
            var temp_path = GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.UploadImgSavePath) + "\\" + DateTime.Now.Year + "\\" + DateTime.Now.ToString("MMdd") + "\\";
            var extension = Path.GetExtension(file_name);
            var file_name_new = DateTime.Now.ToString("yyyyMMddHHmmss") + MiniX.Utility.Helper.CommonHelper.GenerateRandomNum(6);
            var save_path = temp_path + file_name_new + extension;
            var return_path = "/" + DateTime.Now.Year + "/" + DateTime.Now.ToString("MMdd") + "/" + file_name_new + extension;

            try
            {
                if (!Directory.Exists(temp_path))
                {
                    Directory.CreateDirectory(temp_path);
                }

                if (System.IO.File.Exists(save_path))
                {
                    System.IO.File.Delete(save_path);
                }

                using (FileStream fs = System.IO.File.Create(save_path))
                {
                    await formFile.CopyToAsync(fs);
                    fs.Flush();
                }

                using FileStream fi = new FileStream(save_path, FileMode.Open);

                // 上传至阿里云OSS
                try
                {
                    OssClient client = new OssClient(GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunEndpoint), GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunAccessKeyId), GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunAccessKeySecret));
                    var key = "upload/" + DateTime.Now.Year + "/" + DateTime.Now.ToString("MMdd") + "/";
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        client.PutObject(GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunBucketName), key, memStream);
                    }
                    ObjectMetadata metadata = new ObjectMetadata();
                    metadata.ContentType = Request.Form.Files[0].ContentType;
                    client.PutObject(GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunBucketName), key + file_name_new + extension, fi, metadata);
                }
                catch (Exception ex)
                {
                    return Json(new { code = 0, errcode = 40014, errmsg = ex.Message });
                }

                return Json(new { code = 0, msg = "上传成功", data = new { src = GetSettingInfoValue((int)Utility.Helper.ENUMHelper.SettingInfoType.AliyunCallbackServer) + return_path, title = "" } });
            }
            catch (Exception ex)
            {
                return Json(new { code = 0, errcode = 40014, errmsg = ex.Message });
            }
        }
    }
}
